package 课上练习0419_scala_collection

import scala.::

object Scala_03List extends App {
  println("===============创建List====================")
  // 空列表
  val list1 = Nil
  val list2 = List()
  println(list1)

  val fruit = List("apple", "orange", "banana")
  println(fruit)
  val fruit1 = List("apple1", "orange1", "banana1")
  val fruit2 = List(fruit, fruit1)  // 两个组成一个，List(List(apple, orange, banana), List(apple1, orange1, banana1))
  println(fruit2)

  // 1）必须以Nil结尾；
  // 2）默认从右到左结合
  val fruit3 = "apple" :: ("orange" :: ("banana" :: Nil))
  val fruit4 = "apple" :: "orange" :: "banana" :: Nil
  println(fruit3)

  val fruit5: Seq[String] = "apple" :: "orange" :: "banana" :: fruit4 //List(apple, orange, banana, apple, orange, banana)
  val fruit6: Seq[Serializable] = "apple" :: "orange" :: "banana" :: fruit4::Nil //List(apple, orange, banana, List(apple, orange, banana))
  println("不加Nil: " + fruit5)
  println("加Nil: " + fruit6)

  println("===============遍历List====================")
  fruit.foreach(print)
  println()
  println(fruit.mkString(","))

  println("===============List--高阶函数====================")
  // reduce求和
  val list3 = List(1, 2, 3, 4, 5, 6)
  println(list3.reduce(_ + _)) //21
  // 求差
  println(list3.reduceLeft(_ - _)) // 从左往右计算，-19
  println(list3.reduceRight(_ - _)) // 从右往左计算，3，(1 - (2 - (3 - (4 - (5 - 6)))))

  println("===============List--高阶函数-fold====================")
  // fold
  println("fold(10): " + list3.fold(10)((x, y) =>  {
    println(s"x=$x, y=$y")
    x + y
  }))
  println()
  println("foldRight(10): " + list3.foldRight(10)((x, y) =>  {
    println(s"x=$x, y=$y")
    x + y
  }))
  println("===============List--高阶函数-find====================")
  println(list3.find(_ % 2 == 0).getOrElse(-1)) // [1, 2, 3, 4, 5, 6] =>  2
  println(List(2, 4, 6, 8, 3, 5, 7).find(_ % 2 == 0).getOrElse(-1)) // 2
  // takeWhile 从左到右取值，一直取到不符合条件终止
  println(List(2, 4, 6, 8, 3, 5, 7).takeWhile(_ % 2 == 0))//2, 4, 6, 8
  // dropWhile 从左到右丢弃，一直丢到不符合条件终止
  println(List(2, 4, 6, 8, 3, 5, 7).dropWhile(_ % 2 == 0))//3, 5, 7
}
